<?php
set_time_limit(0);
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/15 0015
 * Time: 22:49
 */
register_shutdown_function('micro_benchmark_summary');

$ubm_timing = [];
function micro_benchmark($label, $impl_func, $iterations = 1)
{
    global $ubm_timing;
    print "benchmarking $label ...";
    flush();
    $start = current_user_cpu_rus_age();
    call_user_func($impl_func, $iterations);
    $ubm_timing[$label] = current_user_cpu_rus_age() - $start;
    print  "<br />\n";
    return $ubm_timing;
}

function micro_benchmark_summary()
{
    global $ubm_timing;
    if (empty($ubm_timing)) {
        return;
    }
    arsort($ubm_timing);
    reset($ubm_timing);
    $slowest = current($ubm_timing);
    end($ubm_timing);
    print "<h2>And the winner is: ";
    print key($ubm_timing) . "</h2>\n";
    print "<table border='1'>\n<tr>\n<td>&nbsp;</td>\n";
    foreach ($ubm_timing as $label => $user_cpu) {
        print "<th>$label</th>\n";
    }
    print " </tr>\n";

    $ubm_timing_copy = $ubm_timing;
    foreach ($ubm_timing_copy as $label => $user_cpu) {
        print "<tr>\n <td><b>$label</b><br />";
        printf("%.3fs</td>\n", $user_cpu);
        foreach ($ubm_timing as $label2 => $user_cpu2) {
            $percent = (($user_cpu2 / $user_cpu) - 1) * 100;
            if ($percent > 0) {
                printf("<td>%.3fs<br /> %.1f%% slower", $user_cpu2, $percent);
            } elseif ($percent < 0) {
                printf("<td>%.3fs<br /> %.1f%% faster", $user_cpu2, -$percent);
            } else {
                print "<td>&nbsp;";
            }
            print "</td>\n;";

        }
        print "</tr>\n;";
    }
    print "</table>\n;";
}

function current_user_cpu_rus_age()
{
    $ru = getrusage(); //测量CPU的循环消耗
//    array(6) {
//    'ru_majflt' =>
//  int(2774)
//  'ru_maxrss' =>
//  int(10956)
//  'ru_utime.tv_usec' =>
//  int(31200)
//  'ru_utime.tv_sec' =>
//  int(0)
//  'ru_stime.tv_usec' =>
//  int(31200)
//  'ru_stime.tv_sec' =>
//  int(0)
//}
    return $ru['ru_utime.tv_sec'] + ($ru['ru_utime.tv_usec'] / 1000000.0);
}

//对 str_replace和 preg_replace压测

//$str = 'This string is not modified';
//$loops = 1000000;
//micro_benchmark('str_replace', 'bm_str_replace', $loops);
//micro_benchmark('preg_replace', 'bm_preg_replace', $loops);
//function bm_str_replace($loops)
//{
//    global $str;
//    for ($i = 0; $i < $loops; $i++) {
//        str_replace('is not','has been', $str);
//    }
//}
//
//function bm_preg_replace($loops)
//{
//    global $str;
//    for ($i = 0; $i < $loops; $i++) {
//        preg_replace('/is not/','has been', $str);
//    }
//}